package com.tutou.ikgroup.util;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tutou.ikuser.mapper.UserMapper;
import com.tutou.ikuser.pojo.po.User;
import com.tutou.ikuser.pojo.vo.RedisUser;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.tutou.ikuser.util.RedisConstants.LOGIN_TOKEN_TTL;
import static com.tutou.ikuser.util.RedisConstants.USER_EXIST_KEY;

public class UserCheck {
    //获取用户信息
    public static User token(StringRedisTemplate stringRedisTemplate, String token) {
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(token);
        if (userMap.isEmpty()) {
            return null;
        }
        return BeanUtil.copyProperties(userMap, User.class);
    }

    //用于查询用户是否存在
    @SneakyThrows
    public static User addRedisUser(StringRedisTemplate stringRedisTemplate, String phone, UserMapper userMapper) {
        String receiverStr = stringRedisTemplate.opsForValue().get(USER_EXIST_KEY + phone);
        User receiver = null;
        if (receiverStr != null) {
            receiver = ChangeType.changeTypeStoO(receiverStr, User.class);
        } else {
            receiver = userMapper.selectUser(phone);
            stringRedisTemplate.opsForValue().set(USER_EXIST_KEY + phone, new ObjectMapper().writeValueAsString(new RedisUser(receiver)));
            stringRedisTemplate.expire(USER_EXIST_KEY + phone, LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        }
        return receiver;
    }
}
